import { Bubble, Tools } from 'weaver-mobile';
import axios from 'axios'
export const getFd = (values) => {
    let fd = '';
    for (const p in values) {
        if (values.hasOwnProperty(p)) {
            let target = values[p];
            target = target === void 0 ? '' : target;
            const item = encodeURIComponent(target);
            fd += p + '=' + item + '&';
        }
    }
    return fd;
};
export const getFetchParams = function (method, params, useJson = false) {
    let obj = {
        method,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
            'X-Requested-With': 'XMLHttpRequest',
        }
    };
    if (useJson) {
        obj.headers["Content-Type"] = 'application/json; charset=utf-8'
    }
    if (!window.server) {
        obj.credentials = 'include';
    }
    if (Object.keys(params).length > 0 && method.toUpperCase() !== 'GET') {
        obj.body = getFd(params);
    }
    return obj;
};
export const callApi = function (options) {
    let { url = '', method = 'GET', params = {}, type = 'json', } = options;
    let _url = url;
    const server = window.server || '';
    const ls = Tools.ls;
    if (window.customSessionKey || ls.getJSONObj('customSessionKey')) {
        let customSessionKey = ls.getJSONObj('customSessionKey');
        if (customSessionKey) {
            window.customSessionKey = customSessionKey;
            ls.set('customSessionKey', null);
        } else {
            customSessionKey = window.customSessionKey;
        }
        params[customSessionKey.keyName] = customSessionKey.keyValue;
    }
    _url = `${server}${_url}`;
    if (method.toUpperCase() === 'GET' && Object.keys(params).length > 0) {
        let c = '?';
        if (/\?/.test(_url)) {
            c = '&';
        }
        _url = `${_url}${c}${getFd(params)}`;
    }
    if (method.toUpperCase() === 'GET' && !/__random__/.test(_url)) {
        let c = '?';
        if (/\?/.test(_url)) {
            c = '&';
        }
        _url += c + '__random__=' + new Date().getTime();
    }
    function evil(fn) {
        let Fn = Function; // 一个变量指向Function，防止有些前端编译工具报错
        return new Fn('return ' + fn)();
    }
    let useJson = false
    if (window.longchengRedirect) {
        params['method'] = method;
        params['resourceUri'] = _url;
        let paramsStr = JSON.stringify(params);
        params = {
            ...JSON.parse(window.longchengRedirectParams),
            targetMethod: '/api/ec/dev/http/forward',
            param: paramsStr
        };
        _url = 'http://20.124.164.231:818/httptest/services/IDataTransfer/dataTrans';
        method = 'POST'
        useJson = true;
    }
    return new Promise((resolve, reject) => {
        fetch(_url, getFetchParams(method, params, useJson)).then(function (response) {
            // const reader = response.body.getReader();
            // const processResult = (result: any) => {
            //   console.log('result: ', result);
            //   if (result.done) { return; }
            //   return reader.read().then(processResult);
            // };
            // reader.read().then(processResult);
            return response.text().then((data) => {
                if (window.longchengRedirect) {
                    let res = {};
                    try {
                        res = JSON.parse(data);
                    } catch (e) {
                        res = data || '{}';
                    }
                    if (res.resCode == '10000') {
                        try {
                            return JSON.parse(res.resData);
                        } catch (e) {
                            return evil('(' + res.resData + ')'); // JSON.parse 解析反斜杠报错处理
                        }
                    } else {
                        reject('fail:' + JSON.stringify(data))
                    }
                }
                if (type === 'json') {
                    try {
                        return JSON.parse(data);
                    }
                    catch (error) {
                        data = data || '{}';
                        return evil('(' + data + ')'); // JSON.parse 解析反斜杠报错处理
                    }
                }
                else {
                    return data;
                }
            });
        }).then(data => {
            Bubble.error('success call : ' + JSON.stringify(data));
            if (data && (data.status === 'false' || !data.status)) {
                resolve(data);
            }
            else if (checkReject(data)) {
                reject(`${url} fetch 请求异常: ${data.error || 'error'}`);
            }
            else {
                resolve(data);
            }
        }).catch(function (ex) {
            Bubble.error(JSON.stringify(_url) + 'fail call : ' + JSON.stringify(ex.message) + 'params:' + JSON.stringify(params));
            reject(`${url} fetch 数据处理异常: ${ex}`);
        });

        // axios({
        //     method: method,
        //     url: _url,
        //     data: params
        // })
        // .then(function (response) {
        //   console.log(response);
        // })
        // .catch(function (error) {
        //   console.log(error);
        // });
    });
};
const checkReject = (obj) => {
    let isFalse = false;
    if (obj.errorCode && obj.errorCode === '001') { // session异常
        Bubble.error('session过期');
        isFalse = true;
    }
    else if (obj.errorCode && obj.errorCode === '002') { // session异常
        Bubble.error('登陆超时');
        isFalse = true;
    }
    else if (typeof obj.status !== 'undefined' && (!obj.status || obj.status === 'false')) {
        Bubble.error(JSON.stringify(obj));
        isFalse = true;
    }
    return isFalse;
};
